<template>
  <div>
    <div ref="myMap" style="height: 300px"></div>
  </div>
</template>
<script lang="ts" setup>
import type { EChartsType } from "echarts";
const { $eChart } = useNuxtApp();
const myMap = ref<HTMLElement>();
const props = defineProps({
  data: {
    type: Array as PropType<{ id: string; name: string; value: number }[]>,
    default: () => [],
  },
});
const COLOR = [
  "rgba(47, 123, 230, 1)",
  "rgba(47, 123, 230, 0.85)",
  "rgba(47, 123, 230, 0.7)",
  "rgba(47, 123, 230, 0.55)",
  "rgba(47, 123, 230, 0.4)",
];
const option = {
  grid: {
    top: "8%",
    left: "3%",
    right: "10%",
    bottom: "2%",
    containLabel: true,
  },
  tooltip: {
    trigger: "item",
  },
  xAxis: {
    show: false,
  },
  yAxis: {
    show: true,
    inverse: true,
    type: "category",
    axisLine: {
      show: false,
    },
  },
  series: [
    {
      type: "bar",
      barWidth: 20,
      yAxisIndex: 0,
      label: {
        show: true,
        position: 2,
        fontSize: 15,
      },
      tooltip: { show: false },
    },
    {
      name: "访问次数",
      type: "bar",
      barWidth: 20,
      barMinHeight: 20, // 最小高度
      yAxisIndex: 0,
      label: {
        show: true,
        position: "right",
        fontSize: 18,
        offset: [10, 0],
        formatter({ value }: { value: string }) {
          return `${value}次`;
        },
      },
      tooltip: {
        formatter: "{a}: {c0}",
      },
      itemStyle: {
        barBorderRadius: 4,
      },
    },
  ],
};
let myChart: EChartsType | null = null;
watch(
  () => props.data,
  (newdata) => {
    if (myChart)
      myChart.setOption({
        series: [
          {
            data: newdata.map((item) => {
              return {
                value: 0,
                label: {
                  formatter() {
                    return item.name;
                  },
                },
              };
            }),
          },
          {
            data: newdata.map((item, index) => {
              let color = COLOR[index % COLOR.length];
              return {
                value: item.value,
                label: { color },
                itemStyle: { color },
              };
            }),
          },
        ],
      });
  }
);
onMounted(() => {
  myChart = $eChart.init(myMap.value!);
  // 指定图表的配置项和数据

  // 使用刚指定的配置项和数据显示图表。
  myChart.setOption(option);
});
</script>
